package org.quartz.impl.rmi;

import org.quartz.impl.rmi.entity.*;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.LinkedList;

import static org.quartz.impl.jdbcjobstore.Util.closeStatement;

/**
 * Created by guowei on 2018/1/14.
 */
public class DBWriteThread implements Runnable{
    private String sqlString;
    public LinkedList<ConsumerResponse> result;
    private MutexResource mutex;
    private LinkedList<ProductionRequest> entities;

    public DBWriteThread(String sqlString, MutexResource mutex,
                         LinkedList<ProductionRequest> entities) {
        this.sqlString = sqlString;
        this.mutex = mutex;
        this.entities = entities;
    }

    @Override
    public void run() {
        while(entities.size()!=0){
            mutex.getWLock();
            ConsumerResponse cr = new ConsumerResponse();
            ProductionRequest lle = entities.peek();
            PreparedStatement ps = null;
            try {
                ps = ServerJDBCDriverDelegate.getConn().prepareStatement(sqlString);
                switch(lle.getRequest().getType()){
                    case "UpdateTriggerStatesFromOtherStates":
                        UpdateTriggerStatesFromOtherStates ut = (UpdateTriggerStatesFromOtherStates)lle.getRequest().getAm();
                        ps.setString(1, ut.getNewState());
                        ps.setString(2, ut.getOldState1());
                        ps.setString(3, ut.getOldState2());
                        break;
                    default:
                        cr.setResult(new String("Not Support write-sql."));
                }
                cr.setResult(ps.executeUpdate());
            } catch(SQLException e){
                e.printStackTrace();
                cr.setResult(new Integer(-1));
            } catch(Exception e){
                e.printStackTrace();
                cr.setResult(new Integer(-2));
            } finally {
                closeStatement(ps);
                entities.pop();
                cr.setId(lle.getId());
                result.add(cr);
                mutex.releaseRLock();
            }
        }
    }

    private static String getMethodName(String fildeName) throws Exception{
        byte[] items = fildeName.getBytes();
        items[0] = (byte) ((char) items[0] - 'a' + 'A');
        return new String(items);
    }
}
